package com.suneast.suneaststore.modules.shopcart.adapter;

import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.AppCompatImageView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.shopcart.ShopCartHandler;
import com.suneast.suneaststore.bean.shopcart.ItemGoodsInShopCart;
import com.suneast.suneaststore.bean.shopcart.MultipleItemShopCart;
import com.suneast.suneaststore.modules.shopcart.event.EditCountEvent;
import com.suneast.suneaststore.modules.shopcart.event.EditGoodsEvent;
import com.suneast.suneaststore.modules.shopcart.event.ItemSelectChange;
import com.suneast.suneaststore.modules.shopcart.event.SelectAllChange;
import com.suneast.suneaststore.ui.customview.ZzCheckBox;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MultiShopCartAdapter extends BaseMultiItemQuickAdapter<MultipleItemShopCart, BaseViewHolder> {

    private @Flag.SelectMode
    int selectMode;

    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but navigate
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    public MultiShopCartAdapter(List<MultipleItemShopCart> data) {
        super(data);
        initData();
        addItemType(MultipleItemShopCart.GOODS, R.layout.item_goods_in_cart);
        addItemType(MultipleItemShopCart.SHOP, R.layout.item_shop);
    }

    @Override
    protected void convert(BaseViewHolder helper, MultipleItemShopCart item) {
        if (helper.getItemViewType() == MultipleItemShopCart.SHOP) {
            helper.setText(R.id.shop_name_tv, item.getShopName());
        } else {
            ItemGoodsInShopCart goods = item.getGoods();
            Glide.with(helper.itemView.getContext()).load(goods.getThumb()).into((ImageView) helper.getView(R.id.img_goods));
            helper.setText(R.id.tv_goods_name, goods.getTitle())
                    .setText(R.id.tv_goods_size, goods.getOptionTitle())
                    .setText(R.id.tv_goods_count, "" + goods.getTotal())
                    .setText(R.id.tv_goods_intro_in_edit, goods.getOptionTitle())
                    .setText(R.id.tv_edit_count, "" + goods.getTotal());
            String priceTv = goods.getDiscount() > 0 ?
                    String.format(helper.itemView.getContext().getString(R.string.detail_multiple_price),
                            String.format(locale, "%.2f", goods.getPrice()),
                            String.format(locale, "%.2f", goods.getDiscount())) :
                    String.format(helper.itemView.getContext().getString(R.string.detail_simple_price),
                            String.format(locale, "%.2f", goods.getPrice()));
            helper.setText(R.id.tv_goods_price, priceTv);
            TextView widthHeightTv = helper.getView(R.id.tv_custom_info);
            if (goods.getHeight() != 0 && goods.getWidth() != 0) {
                widthHeightTv.setVisibility(View.VISIBLE);
                widthHeightTv.setText(String.format(helper.itemView.getContext()
                                .getResources().getString(R.string.width_height),
                        String.format(locale, "%.2f", goods.getWidth()),
                        String.format(locale, "%.2f", goods.getHeight())));
            } else {
                widthHeightTv.setVisibility(View.INVISIBLE);
            }
            ZzCheckBox zzCheckBox = helper.getView(R.id.select_box);
            zzCheckBox.setTag(goods.getId());
            zzCheckBox.setChecked(goods.isSelected());
            cbList.add(zzCheckBox);
            zzCheckBox.setOnCheckedChangeListener((View v, boolean isChecked) -> {
                if (selectMode == Flag.SelectMode.SELECT) {
                    ShopCartHandler.selectOrUnSelectGoods(goods.getId());
                } else {
                    EventBus.getDefault().post(new ItemSelectChange(isChecked, goods.getId()));
                }
            });
            AppCompatImageView showEditBtn = helper.getView(R.id.img_edit_item_shop_cart);
            ConstraintLayout itemEditLayout = helper.getView(R.id.item_edit_layout);
            itemEditLayout.setVisibility(View.GONE);
            showEditBtn.setOnClickListener((View v) -> {
                itemEditLayout.setVisibility(View.VISIBLE);
                helper.setText(R.id.tv_goods_intro_in_edit, goods.getOptionTitle())
                        .setText(R.id.tv_edit_count, "" + goods.getTotal());
                EventBus.getDefault().post(new EditGoodsEvent(true, item.getGoods()));
            });
            TextView countText = helper.getView(R.id.tv_edit_count);
            Button cutCountBtn = helper.getView(R.id.btn_cut_count);
            cutCountBtn.setOnClickListener((View v) -> {
                int count = Integer.valueOf(countText.getText().toString());
                if (count > 1) {
                    countText.setText(String.valueOf(count - 1));
                    EventBus.getDefault().post(new EditCountEvent(false, item.getGoods().getId()));
                }
            });
            Button addCountBtn = helper.getView(R.id.btn_add_count);
            addCountBtn.setOnClickListener((View v) -> {
                int count = Integer.valueOf(countText.getText().toString());
                if (count < item.getGoods().getStock()) {
                    countText.setText(String.valueOf(count + 1));
                    EventBus.getDefault().post(new EditCountEvent(true, item.getGoods().getId()));
                }
            });
            Button finishEditBtn = helper.getView(R.id.btn_finish_edit);
            finishEditBtn.setOnClickListener((View v) -> {
                itemEditLayout.setVisibility(View.GONE);
                EventBus.getDefault().post(new EditGoodsEvent(false, item.getGoods()));
            });
            helper.addOnClickListener(R.id.img_goods)
                    .addOnClickListener(R.id.tv_goods_intro_in_edit)
                    .addOnClickListener(R.id.img_arrow_down);
        }
    }

    private ArrayList<ZzCheckBox> cbList;

    private Locale locale;

    private void initData() {
        cbList = new ArrayList<>();
        selectMode = Flag.SelectMode.SELECT;
        locale = new Locale("zh");
    }

    public List<ZzCheckBox> getCbList() {
        return cbList;
    }

    public @Flag.SelectMode
    int getSelectMode() {
        return selectMode;
    }

    public void setSelectMode(@Flag.SelectMode int selectMode) {
        this.selectMode = selectMode;
    }

    @Override
    public void onViewAttachedToWindow(BaseViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onViewDetachedFromWindow(@NonNull BaseViewHolder holder) {
        EventBus.getDefault().unregister(this);
        super.onViewDetachedFromWindow(holder);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelectAllChangeEvent(SelectAllChange event) {
        doSelect(event.isSelect());
    }

    private void doSelect(boolean isSelect) {
        for (int i = 0, length = cbList.size(); i < length; i++) {
            cbList.get(i).setChecked(isSelect);
        }
    }
}
